package cuongnh.project.japanesediary.vocabulary.ui.view.action.menucontribution.category.sentences;

import java.util.Set;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import cuongnh.project.japanesediary.vocabulary.common.CommonServices;
import cuongnh.project.japanesediary.vocabulary.model.Category;
import cuongnh.project.japanesediary.vocabulary.model.Sentence;
import cuongnh.project.japanesediary.vocabulary.ui.dialog.AddRelatedSentenceDialog;
import cuongnh.project.japanesediary.vocabulary.ui.view.CategorySentencesView2;

public class AddCategorySentenceAction2 implements IViewActionDelegate {

	public static final String ID = "cuongnh.project.japanesediary.vocabulary.action.AddCategorySentence2";

	protected IViewPart m_view;
	
	protected TableViewer tableViewer;

	private CommonServices commonServices;

	private Category category;
	
	private Set<Sentence> selectedSentences;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)
	 */
	@Override
	public void init(IViewPart view) {
		m_view = view;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	@Override
	public void run(IAction action) {
		// 履歴ビュー更新
		CategorySentencesView2 view = (CategorySentencesView2) m_view
				.getAdapter(CategorySentencesView2.class);
		commonServices = view.getCommonServices();
		category = view.getSelectedCategory();
		AddRelatedSentenceDialog relatedSentenceDialog = new AddRelatedSentenceDialog(
				view.getSite().getShell(), commonServices);
		if (relatedSentenceDialog.open() == Window.OK) {
			selectedSentences = relatedSentenceDialog
					.getSelectedSentences();
			if (!selectedSentences.isEmpty()) {
				// update selected vocabulary to current category
				Category currentCategory = commonServices.getCategoryDao()
						.getCategoryWithSentences(category.getCategoryId());
				currentCategory.getSentences().addAll(selectedSentences);
				commonServices.getCategoryDao().update(currentCategory);
			}
		}
		view.update();
		tableViewer = view.getTblvSentences();
		tableViewer.setSelection(new StructuredSelection(selectedSentences.toArray()));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action
	 * .IAction, org.eclipse.jface.viewers.ISelection)
	 */
	@Override
	public void selectionChanged(IAction action, ISelection selection) {

	}

}
